package com.qf.mybatisplus.websocket;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{clientId}")
@Component
public class WebSocket {

    private final static Logger logger = LoggerFactory.getLogger(WebSocket.class);
    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String clientId;


    @OnOpen
    public void onOpen(@PathParam("clientId") String clientId,Session session) throws IOException {


        this.session = session;
        addOnlineCount();
        this.clientId = clientId;
        clients.put(clientId, this);
        System.err.println(clientId+"websocket已连接");
        System.err.println("在线数："+onlineCount);
    }

    @OnClose
    public void onClose() throws IOException {
        subOnlineCount();
        System.err.println(clientId+"连接已关闭");
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        System.err.println(message);

        sendMessageAll("服务器返回数据："+message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
        //logger.info("{}离线断网了",machineId);
        System.out.println(clientId + "断网了");
    }

    public static void sendMessageTo(String message, String To) throws IOException {
        // session.getBasicRemote().sendText(message);
        //session.getAsyncRemote().sendText(message);
        for (WebSocket item : clients.values()) {
            if (item.clientId.equals(To)) {
                // 向客户端发送消息
                item.session.getAsyncRemote().sendText(message);
            }
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
          WebSocket.onlineCount--;
    }

    public static synchronized Map<String, WebSocket> getClients() {
        return clients;
    }

}
